<template>
    <div>
        <van-nav-bar title="频道管理" left-arrow
        @click-left="$router.back()">
        </van-nav-bar>
        <div class="content">
            <h1 class="title">点击删除频道</h1>
            <van-grid :gutter="10" :column-num="4">
                <van-grid-item @click="delFn(index)" v-for="(value,index) in categoryList" :key="value.id" :text="value.name" />
            </van-grid>
        </div>
        <div class="content">
            <h1 class="title">点击添加频道</h1>
            <van-grid :gutter="10" :column-num="4">
                <van-grid-item @click="addFn(index)" v-for="(value,index) in delCategoryList" :key="value.id" :text="value.name" />
            </van-grid>
        </div>
    </div>
</template>

<script>
import {category} from "@/api/common.js"
export default {
    data(){
        return {
            categoryList: JSON.parse(localStorage.getItem("categoryList"))||[],
            delCategoryList: JSON.parse(localStorage.getItem("delCategoryList"))||[],
            defaultCategory: [] // 默认栏目 不能删除 关注和头条
        }
    },
    created(){
        // 如果缓存中存在栏目数据，则不需要从接口获取栏目列表，否则需
        if(this.categoryList.length==0&&this.delCategoryList.length==0){
            category().then(res=>{
                // console.log(26,res);
                this.categoryList = res.data.data;
                // 判断用户是否登录，登录了删除前2个数据（关注和头条），未登录只需删除头条（因为没有关注这个栏目）
                if(localStorage.getItem("72-token")){
                    this.defaultCategory = this.categoryList.splice(0,2)
                }else{
                    this.defaultCategory = this.categoryList.splice(0,1)    
                }
                localStorage.setItem("defaultCategory",JSON.stringify(this.defaultCategory))
            })
        }
    },
    methods: {
        delFn(index){
            // console.log(index);
            let res = this.categoryList.splice(index,1)
            // console.log(res);res就是被删除的数据（注意：是一个数组）
            this.delCategoryList.push(...res);
        },
        addFn(index){
            let res = this.delCategoryList.splice(index, 1);
            this.categoryList.push(...res);
        }
    },
    watch: {
        categoryList: {
            deep: true,
            handler(){
                // 同时缓存两个数组
                localStorage.setItem("categoryList", JSON.stringify(this.categoryList))
                localStorage.setItem("delCategoryList", JSON.stringify(this.delCategoryList))
            }
        }
    }
}
</script>

<style lang="less" scoped>
.content{
    margin-top: 10px;
    padding: 0 5px;
    h1{
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 20px;
        margin-top: 20px
    }
    /deep/.van-grid-item__content{
        border: 1px solid #666;
    }
}
</style>